<template>
  <div class="app-container">
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd" :disabled="addButFlag" >新增节点</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="el-icon-edit" size="mini" @click="handleUpdate" :disabled="updateButFlag" >修改节点</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="el-icon-delete" size="mini" @click="handleDelete" :disabled="deleteButFlag" >删除节点</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="el-icon-video-play" size="mini" @click="handleTestAll" >数据集整体测试</el-button>
      </el-col>
    </el-row>
    <div id="jsmind_container" @click="get_node" ></div>
    <el-dialog :title="title" :visible.sync="open" width="1024px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="90px">
        <el-row>
          <el-col :span="8">
            <el-form-item label="数据集名称" prop="name">
              <el-input v-model="form.name" placeholder="请输入数据集名称" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="数据集代码" prop="code">
              <el-input v-model="form.code" placeholder="请输入数据集代码" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="数据集类型" prop="type">
              <el-select v-model="form.type" placeholder="请选择数据集类型">
                <el-option
                  v-for="dict in typeOptions"
                  :key="dict.dictValue"
                  :label="dict.dictLabel"
                  :value="dict.dictValue"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="执行SQL语句" prop="SQL">
              <el-input v-model="form.SQL" type="textarea" placeholder="请输入内容" />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="启停状态">
              <el-radio-group v-model="form.status">
                <el-radio
                  v-for="dict in statusOptions"
                  :key="dict.dictValue"
                  :label="dict.dictValue"
                >{{dict.dictLabel}}</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="参数">
              <el-row :gutter="10" class="mb8">
                <el-col :span="1.5">
                  <el-button
                    type="primary"
                    plain
                    icon="el-icon-plus"
                    size="mini"
                    @click="getParameter"

                  >根据SQL语句获取参数</el-button>
                </el-col>
              </el-row>
              <el-table v-loading="ParameterLoading" :data="setParameterList" >
                <el-table-column type="selection" width="55" align="center" />
                <el-table-column label="参数名称" align="center" prop="name" />
                <el-table-column label="参数代码" align="center" prop="code" />
                <el-table-column label="参数类型" align="center" prop="type" />
                <el-table-column label="参数顺序" align="center" prop="sort" />
                <el-table-column label="默认值" align="center" prop="default" />
                <el-table-column label="启停状态" align="center" prop="status" :formatter="statusFormat" />
                <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
                  <template slot-scope="scope">
                    <el-button
                      size="mini"
                      type="text"
                      icon="el-icon-edit"
                      @click="handleUpdateParameter(scope.row)"
                    >修改</el-button>

                  </template>
                </el-table-column>
              </el-table>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="testDataSet">测试数据集</el-button>
        <el-button type="primary" @click="saveDataSet">保 存</el-button>
        <el-button @click="cancelDataSet">取 消</el-button>
      </div>
    </el-dialog>



    <el-dialog :title="parameterTitle" :visible.sync="openParameter" width="1024px" append-to-body>
      <el-form ref="form" :model="parameterForm" :rules="rules" label-width="90px">
        <el-row>
          <el-col :span="8">
            <el-form-item label="参数名称" prop="name">
              <el-input v-model="parameterForm.name" placeholder="请输入数据集名称" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="参数代码" prop="code">
              <el-input v-model="parameterForm.code" placeholder="请输入数据集代码" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="参数类型" prop="type">
              <el-select v-model="parameterForm.type">
                <el-option label="Long" value="Long" />
                <el-option label="String" value="String" />
                <el-option label="Integer" value="Integer" />
                <el-option label="Double" value="Double" />
                <el-option label="BigDecimal" value="BigDecimal" />
                <el-option label="Date" value="Date" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="参数顺序" prop="sort">
              <el-input v-model="parameterForm.sort" disabled="false" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="参数默认值" prop="default">
              <el-input v-model="parameterForm.default"/>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="启停状态">
              <el-radio-group v-model="parameterForm.status">
                <el-radio
                  v-for="dict in statusOptions"
                  :key="dict.dictValue"
                  :label="dict.dictValue"
                >{{dict.dictLabel}}</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>

        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">

        <el-button type="primary" @click="submitParameterForm">保 存</el-button>
        <el-button @click="cancelParameterForm">取 消</el-button>
      </div>
    </el-dialog>



  </div>
</template>

<script>
import { listSet, getSet, delSet, addSet, updateSet, testSet,testAllSet,getInfo } from "@/api/tool/dataManage/dataSet";
import 'jsmind/style/jsmind.css'
import jsMind from 'jsmind/js-legacy/jsmind.js'

window.jsMind = jsMind
require('jsmind/js-legacy/jsmind.draggable-node.js')
require('jsmind/js-legacy/jsmind.screenshot.js')
export default {
  name: "setDetail",
  components: {
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      ParameterLoading:true,
      // 导出遮罩层
      exportLoading: false,
      // 选中数组
      ids: [],
      //添加按钮启用
      addButFlag:false,
      updateButFlag:false,
      deleteButFlag:false,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 数据集主表格数据
      setList: [],
      setParameterList:[],
      setFieldList:[],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 数据集类型字典
      typeOptions: [],
      // 启停状态字典
      statusOptions: [],
      // 表单参数
      form: {},
      nodeFlag:"add",
      // 表单校验
      rules: {
        SQL: [
          { required: true, message: "执行数据集SQL语句不能为空", trigger: "blur" }
        ],
        status: [
          { required: true, message: "启停状态不能为空", trigger: "blur" }
        ]
      },
      openParameter:false,
      parameterTitle:"修改参数",
      parameterForm:{},
      mind: {
        /* 元数据，定义思维导图的名称、作者、版本等信息 */
        meta: {
          name: '思维导图',
          author: '133313112@qq.com',
          version: '1.0'
        },
        /* 数据格式声明 */
        format: 'node_tree',
        /* 数据内容 */
        data: {
        }
      },
      options: {
        container: 'jsmind_container', // [必选] 容器的ID
        editable: false, // [可选] 是否启用编辑
        theme: 'orange', // [可选] 主题
        view: {
          engine: 'canvas', // 思维导图各节点之间线条的绘制引擎
          hmargin: 120, // 思维导图距容器外框的最小水平距离
          vmargin: 50, // 思维导图距容器外框的最小垂直距离
          line_width: 2, // 思维导图线条的粗细
          line_color: '#ddd' // 思维导图线条的颜色
        },
        layout: {
          hspace: 100, // 节点之间的水平间距
          vspace: 20, // 节点之间的垂直间距
          pspace: 20 // 节点与连接线之间的水平间距（用于容纳节点收缩/展开控制器）
        },
        shortcut: {
          enable: false // 是否启用快捷键 默认为true
        }
      },
    };
  },
  created() {

    this.getDicts("dataSetType").then(response => {
      this.typeOptions = response.data;
    });
    this.getDicts("sys_normal_disable").then(response => {
      this.statusOptions = response.data;
    });
    if(this.mind.data.id)
    {
      this.addButFlag=true;
      this.updateButFlag=true;
      this.deleteButFlag=true;
    }
    else
    {
      this.addButFlag=false;
      this.updateButFlag=true;
      this.deleteButFlag=true;
    }
  },
  mounted() {
    //初始化结构
    this.info();

  },
  methods: {
    handleTestAll()
    {
      var that=this
      testAllSet(this.$route.query.id).then(res => {
        if(res.code=='200')
        {
          that.$alert(res.data, '测试结果', {
            confirmButtonText: '确定'
          }, { customClass: 'my-custom-class' });
        }
        else
        {
          that.$message.error(res.msg);
        }
      });
    },
    cancelDataSet()
    {
      this.resetForm();
      this.open=false;
    },
    resetForm()
    {
      this.form={
        name:"",
        code:"",
        type:"",
        SQL:"",
        status:"0",
        parameters:[],
        fields:[],
        pid:""
      }
      this.setParameterList=this.form.parameters
    },
    saveDataSet()
    {
      // 获取状态判断节点是否为新增或者更新
      var that=this;


      updateSet(this.form).then(response => {

          if(response.code=='200')
          {
            if(response.data.pid=='-1')
            {
              that.$route.query.id=response.data.id;
            }
            that.$message.success('保存成功！');
            that.open=false;

            if (that.nodeFlag=="add")
            {
              that.jm.enable_edit();
              that.jm.add_node(that.jm.get_selected_node(),response.data.id,response.data.name,response.data)
              that.jm.disable_edit();
            }
            if (that.nodeFlag=="update")
            {
              that.jm.enable_edit();
              that.jm.update_node(response.data.id,response.data.name)
              that.jm.disable_edit();
            }
            if(that.nodeFlag=="root")
            {

              // this.$router.replace({ path: "/dataSetDetails", query: {"id":response.data.id}})
              that.close();

            }

          }
          else{
            that.$message.error('保存失败！');
          }

      })
    },
    testDataSet()
    {
      var that=this
      this.$confirm('测试['+this.form.name+']数据集前先保存配置想，是否保存配置项并测试？', "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(function() {
        if(that.verification()=="200")
        {
          updateSet(that.form).then(response => {
            testSet(response.data.id).then(res => {
              if(res.code=='200')
              {
                that.$alert(res.data, '测试结果', {
                  confirmButtonText: '确定'
                });
              }
              else
              {
                that.$message.error(res.msg);
              }
            });
          });
        }
        else
        {
          if(that.verification()=="501")
          {
            that.$message.error('入参默认值不能为空，测试数据集失败！');
          }
          if(that.verification()=="502")
          {
            that.$message.error('SQL语句入参和参数不匹配！');
          }
        }
      }).then(() => {
      })
    },
    verification()
    {

      if(this.form.SQL.split("?").length-1==this.setParameterList.length)
      {
        var flagTest=true;
        this.setParameterList.forEach(function(item, index, arr) {
          if(!item.default) {
            flagTest=false;
          }
        });
        if(flagTest)
        {
          return "200";
        }
        else
        {
          return "501";
        }
      }
      else
      {
        return "502";
      }
    },
    submitParameterForm()
    {
      for(var i=0;i<this.setParameterList.length;i++)
      {
        var parame=this.setParameterList[i];
        if(parame.sort==this.parameterForm.sort)
        {
          parame.name=this.parameterForm.name
          parame.code=this.parameterForm.code
          parame.type=this.parameterForm.type
          parame.default=this.parameterForm.default
          parame.status=this.parameterForm.status
        }
      }
      this.openParameter = false;
    },
    cancelParameterForm()
    {
      this.openParameter = false;
    },
    handleUpdateParameter(row)
    {
      this.openParameter = true;
      this.parameterTitle = "修改参数";
      this.parameterForm=row;

    },
    handleDeleteParameter(row)
    {
      this.setParameterList.forEach(function(item, index, arr) {
        if(item.sort === row.sort) {
          arr.splice(index, 1);
        }
      });
    },
    getParameter()
    {

      var count=this.form.SQL.split("?").length-1;
      for(var i=1;i<=count;i++)
      {
        var param={"name":"参数"+i,"code":"param"+i,"type":"String","sort":i,"default":"","status":"0"};
        this.setParameterList.push(param)
      }
    },
    typeFormat(row, column)
    {

    },
    statusFormat(row, column) {
      return this.selectDictLabel(this.statusOptions, row.status);
    },
    info(){

      getInfo(this.$route.query.id).then(response => {
        if(response.code=="200")
        {
          this.mind.data=response.data;
          this.jm = jsMind.show(this.options, this.mind)
        }
      });
    },
    get_node()
    {
      if(this.jm.get_selected_node())
      {
        this.addButFlag=false;
        this.updateButFlag=false;
        this.deleteButFlag=false;
      }
      else {
        if(this.mind.data!=null)
        {
          this.addButFlag=true;
          this.updateButFlag=true;
          this.deleteButFlag=true;
        }
        else
        {
          this.addButFlag=false;
          this.updateButFlag=true;
          this.deleteButFlag=true;
        }
      }

    },
    handleAdd()
    {
      this.open = true;
      this.ParameterLoading=false
      this.title = "添加节点";
      this.form={
        pid:"",
        name:"",
        code:"",
        type:"",
        SQL:"",
        status:"0",
        parameters:[],
        fields:[]
      }
      this.setParameterList=this.form.parameters;
      if(this.mind.data.id)
      {
        //已经有了根节点，需要选中跟节点才能新增
        if(this.jm.get_selected_node().id)
        {
          this.form.pid=this.jm.get_selected_node().id
        }
        else
        {
          this.$message.error('请选中节点后新增子节点！');
        }
      }
      else
      {
        //没有根节点的时候创建根节点
        this.form.pid=-1;
        this.nodeFlag="root"
      }
    },
    handleUpdate()
    {
      this.open = true;
      this.title = "修改节点";
      if(this.jm.get_selected_node())
      {
        this.nodeFlag="update"
        //已经有了根节点，需要选中跟节点才能新增
        getSet(this.jm.get_selected_node().id).then(response => {
          if(response.code=="200")
          {
            this.form=response.data
            this.setParameterList=response.data.parameters
            this.setFieldList==response.data.fields
            this.ParameterLoading=false
          }
        });
      }
      else
      {
        this.$message.error('请选中节点后编辑！');
      }
    },
    handleDelete()
    {
      var that=this;
      if(this.jm.get_selected_node())
      {
        this.$confirm('是否确认删除选中数据节点其子节点?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          delSet([that.jm.get_selected_node().id]).then(response => {
            if(response.code=='200')
            {
              that.jm.enable_edit();
              that.$message.success('删除成功！');
              that.jm.remove_node(that.jm.get_selected_node().id)
              that.jm.disable_edit();

            }
            else
            {
              that.$message.error('删除失败！');
            }
          });
        })
      }
      else
      {
        this.$message.error('请选中节点后删除！');
      }
    }
  }
}
</script>

<style scoped lang="scss">
  #jsmind_container {
    width: 100%;
    height: 80vh;
  }
  my-custom-class{
    width: 900px;
  }
</style>
